from google.appengine.ext import db

import math

class Location(db.Model):
    zipCode = db.IntegerProperty()
    street = db.StringProperty()
    number = db.IntegerProperty()
    lat = db.FloatProperty()
    lng = db.FloatProperty()

    def save(self):
        self.put()
        self.id = self.key().id

    def string(self):
        return "{0} {1}, {2}".format(self.street, self.number, self.zipCode)

def LoadLocationDefault():
    locationQ = db.GqlQuery("SELECT * FROM Location WHERE zipCode=:1", -1)
    location = locationQ.get()
    if not location:
        location = Location()
        location.zipCode = -1
        location.lat = 55.675771
        location.lng = 12.569312
        location.put()
    return location

def Distance(l1, l2):
    R = 6371 # km
    dLat = math.radians(l2.lat-l1.lat)
    dLon = math.radians(l2.lng-l1.lng)
    lat1 = math.radians(l1.lat)
    lat2 = math.radians(l2.lat)
    a = math.sin(dLat/2.0) * math.sin(dLat/2.0) + math.sin(dLon/2.0) * math.sin(dLon/2) * math.cos(lat1) * math.cos(lat2)
    c = 2.0 * math.atan2(math.sqrt(a), math.sqrt(1-a));
    d = R * c;
    return d


def LoadLocation(idt):
    key = db.Key.from_path('Location', long(idt))
    location = db.get(key)
    location.id = idt
    return location

